<?php

namespace app\common\model\dealer;

use app\common\model\BaseModel;

/**
 * 分销商用户模型
 * Class Apply
 * @package app\common\model\dealer
 */
class User extends BaseModel
{
    protected $name = 'dealer_user';

    /**
     * 强制类型转换
     * @var array
     */
    protected $type = [
        'first_num' => 'integer',
        'second_num' => 'integer',
        'third_num' => 'integer',
    ];

    protected $append = [
        'identity_text'
    ];

    public function getIdentityTextAttr($value, $data)
    {
        $text = ['', 'VIP', '初级团长', '高级团长'];
        return $text[$data['identity']];
    }

    /**
     * 关联会员记录表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\common\model\User');
    }

    /**
     * 关联推荐人表
     * @return \think\model\relation\BelongsTo
     */
    public function referee()
    {
        return $this->belongsTo('app\common\model\User', 'referee_id')
            ->field(['user_id', 'nickName']);
    }

    /**
     * 获取分销商用户信息
     * @param $userId
     * @param array $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($userId, $with = ['user', 'referee'])
    {
        return self::get($userId, $with);
    }

    /**
     * 是否为分销商
     * @param $userId
     * @return bool
     */
    public static function isDealerUser($userId)
    {
        return !!(new static)->where('user_id', '=', $userId)
            ->where('is_delete', '=', 0)
            ->value('user_id');
    }

    /**
     * 新增分销商用户记录
     * @param $user_id
     * @param $data
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function add($user_id, $data)
    {
        $model = static::detail($user_id) ?: new static;
        return $model->save(array_merge([
            'user_id' => $user_id,
            'is_delete' => 0,
            'wxapp_id' => $model::$wxapp_id
        ], $data));
    }

    /**
     * 发放分销商佣金
     * @param $user_id
     * @param $money
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function grantMoney($user_id, $money)
    {
        // 分销商详情
        $model = static::detail($user_id);
        if (!$model || $model['is_delete']) {
            return false;
        }
        // 累积分销商可提现佣金
        $model->setInc('money', $money);
        // 记录分销商资金明细
        Capital::add([
            'user_id' => $user_id,
            'flow_type' => 10,
            'money' => $money,
            'describe' => '订单佣金结算',
            'wxapp_id' => $model['wxapp_id'],
        ]);
        return true;
    }

    ############################ 2020-05-27 新增开始 #########################################
    /**
     * 获取分销商信息
     */
    public static function getByUserID($user_id)
    {
        return self::where('user_id', $user_id)->where('is_delete', 0)->find();
    }

    /**
     * 首次申请或升级初级团长
     */
    public static function applyOrUpgrade($user_id, $data, $type)
    {
        $dealerUser = self::getByUserID($user_id);
        if ($dealerUser) {
            $dealerUser->real_name = $data['real_name'] ?? $dealerUser->real_name;
            $dealerUser->mobile = $data['mobile'] ?? $dealerUser->mobile;
            //上级
            $refereeUser = self::getByUserID($dealerUser['referee_id']);
            //晋升为初级
            if ($type == 2) {
                $dealerUser->identity = 2;
                if ($refereeUser && $refereeUser->identity == 2) {
                    //跟以前上级同级
                    $dealerUser->before_referee_id = $refereeUser->user_id;
                    $dealerUser->referee_id = $refereeUser->referee_id;
                }
            }
            //晋升为高级
            if ($type == 3) {
                //断开以前关系
//                self::where('before_referee_id', $user_id)->update(['before_referee_id' => 0]);
                $dealerUser->before_referee_id = 0;
                $dealerUser->identity = 3;
                $dealerUser->referee_id = 0;
                if ($refereeUser && $refereeUser->identity == 3) {
                    //跟以前上级同级
                    $dealerUser->before_referee_id = $refereeUser->user_id;
                }
                //重新找回以前的下级
                $ids = self::where('before_referee_id', $user_id)->column('user_id');
                self::whereIn('user_id', $ids)->update(['referee_id' => $user_id, 'before_referee_id' => 0]);

            }
            $dealerUser->save();
        } else {
            //新增
            self::add($user_id, [
                'real_name' => $data['real_name'],
                'mobile' => $data['mobile'],
                'identity' => $type
            ]);
        }
    }

    /**
     * 获取一级用户id
     */
    public static function getUserByRefereeId($user_id)
    {
        return self::where('referee_id', $user_id)->column('user_id');
    }

    /**
     * 获取下级用户id
     */
    public static function getUserInRefereeId($user_ids)
    {
        return self::whereIn('referee_id', $user_ids)->where('referee_id', '>', 0)->column('user_id');
    }

    /**
     * 获取一二三级用户id
     */
    public static function getLevelUserIds($user_id, $level)
    {
        $firstUserIds = static::getUserByRefereeId($user_id);
        $secondUserIds = static::getUserInRefereeId($firstUserIds);
        $thirdUserIds = static::getUserInRefereeId($secondUserIds);
        switch ($level) {
            case 1:
                return $firstUserIds;
                break;
            case 2:
                return $secondUserIds;
                break;
            case 3:
                return $thirdUserIds;
                break;
            default:
                return [];
                break;
        }
    }
    /**
     * 下级用户信息
     */
    public static function getUnderlingList($user_id, $level)
    {
        $userIds = self::getLevelUserIds($user_id, $level);
        return self::with('user')->whereIn('user_id',$userIds)->order('create_time desc')->paginate(15);
    }
    ############################ 2020-05-27 新增结束 #########################################
}